/*
 * @Author: yuki
 * @Date: 2025-11-05 15:00:00
 * @LastEditTime: 2025-11-05 20:49:49
 * @Description: 统一响应格式化拦截器
 */
import type { Response as ResponseFormat } from '@horoscope/shared';
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor
} from '@nestjs/common';
import { Response } from 'express';
import { Observable, map } from 'rxjs';

type GenericWithMessage = { message?: string } | null | undefined;

@Injectable()
export class ResponseInterceptor<T extends GenericWithMessage>
  implements NestInterceptor<T, ResponseFormat<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Observable<ResponseFormat<T>> {
    // 获取HTTP响应对象
    const response = context.switchToHttp().getResponse<Response>();
    // 获取HTTP状态码
    const statusCode = response.statusCode;

    return next.handle().pipe(
      map((data: T) => {
        // 统一格式化响应
        return {
          code: statusCode,
          message: data?.message ?? this.getStatusMessage(statusCode),
          data: data || null,
          success: true
        };
      })
    );
  }

  // 根据状态码获取默认消息
  private getStatusMessage(statusCode: number): string {
    const statusMessages: Record<number, string> = {
      200: '请求成功',
      201: '创建成功',
      400: '请求参数错误',
      401: '未授权',
      403: '禁止访问',
      404: '资源不存在',
      500: '服务器内部错误'
    };

    return statusMessages[statusCode] || '操作成功';
  }
}
